package com.self.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.shortlink.admin.common.biz.user.UserContext;
import com.self.shortlink.admin.common.convention.exception.ClientException;
import com.self.shortlink.admin.common.convention.exception.ServiceException;
import com.self.shortlink.admin.common.convention.result.Result;
import com.self.shortlink.admin.dao.entity.GroupDO;
import com.self.shortlink.admin.dao.entity.GroupUniqueDO;
import com.self.shortlink.admin.dao.mapper.GroupMapper;
import com.self.shortlink.admin.dao.mapper.GroupUniqueMapper;
import com.self.shortlink.admin.dto.resp.ShortLinkGroupSortRespDTO;
import com.self.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.self.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.self.shortlink.admin.remote.ShortLinkActualRemoteService;
import com.self.shortlink.admin.remote.dto.resp.ShortLinkGroupCountRespDTO;
import com.self.shortlink.admin.service.GroupService;
import com.self.shortlink.admin.toolkit.RandomGenerator;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.dao.DuplicateKeyException;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.self.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * 短链接分组接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final ShortLinkActualRemoteService shortLinkActualRemoteService;
    private final RedissonClient redissonClient;
    private final RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;
    private final GroupUniqueMapper groupUniqueMapper;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String groupName) {
       saveGroup(UserContext.getUsername(), groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        // 添加分布式锁（分组保存），防止分组读写冲突
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY,username));
        // 进行分布式锁，防止分组读写冲突
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            // 分组不为空且到达上限
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }
            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while (retryCount < maxRetries) {
                // 最多尝试生成  maxRetries 次分组标识
                gid = saveGroupUniqueReturnGid();
                // 分组标识如果之前未存在，则建立并添加到布隆过滤器（分组注册）中
                if (StrUtil.isNotEmpty(gid)) {
                    GroupDO groupDO = GroupDO.builder()
                            .gid(gid)
                            .sortOrder(0)
                            .username(username)
                            .name(groupName)
                            .build();
                    baseMapper.insert(groupDO);
                    gidRegisterCachePenetrationBloomFilter.add(gid);
                    break;
                }
                retryCount++;
            }
            //  maxRetries 次分组标识建立失败，则抛异常
            if (StrUtil.isEmpty(gid)) {
                throw new ServiceException("生成分组标识频繁");
            }
        } finally {
            lock.unlock();
        }
    }


    private boolean hasGid(String username, String gid) {
        // 查询分组标识是否已存在（弃用，现在不在数据库中查，在布隆过滤器中查）
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getName, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag == null;
    }

    private String saveGroupUniqueReturnGid() {
        // 生成6位长度的随机数，数包括数字、大写字母、小写字母
        String gid = RandomGenerator.generateRandom();
        // 布隆过滤器（分组注册）已存在该分组标识，返回null
        if (gidRegisterCachePenetrationBloomFilter.contains(gid)) {
            return null;
        }
        // 布隆过滤器（分组注册）不存在该分组标识，返回gid
        GroupUniqueDO groupUniqueDO = GroupUniqueDO.builder()
                .gid(gid)
                .build();
        try {
            groupUniqueMapper.insert(groupUniqueDO);
        } catch (DuplicateKeyException e) {
            return null;
        }
        return gid;
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        // 按指定排序方法查询当前用户分组
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);

        // 调用 project 查询分组短链接数量
        Result<List<ShortLinkGroupCountRespDTO>> listResult = shortLinkActualRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);

        // 下面一段代码记录当前用户分组每条短链接访问信息（IP,UIP,UP）
        // 当前用户分组每条记录记为 each 遍历
        shortLinkGroupRespDTOList.forEach(each -> {
            // 从所有分组短链接中筛选出与当前 each 的分组标识相等的记录，找到第一项
            Optional<ShortLinkGroupCountRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            // 如果寻找的 first 不为空，则将 first 的 shortLinkCount 赋值给 each 的 shortLinkCount
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        // 根据分组标识以及用户名更新分组名称
        LambdaQueryWrapper<GroupDO> updateWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO, updateWrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        // 根据分组标识以及用户名删除分组
        LambdaQueryWrapper<GroupDO> deleteWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, deleteWrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortRespDTO> requestParam) {
       requestParam.forEach(each -> {
           GroupDO groupDO = GroupDO.builder()
                   .sortOrder(each.getSortOrder())
                   .build();
           LambdaQueryWrapper<GroupDO> updateWrapper = Wrappers.lambdaQuery(GroupDO.class)
                   .eq(GroupDO::getGid, each.getGid())
                   .eq(GroupDO::getUsername, UserContext.getUsername())
                   .eq(GroupDO::getDelFlag, 0);
           baseMapper.update(groupDO, updateWrapper);
       });
    }
}
